/*
Copyright (c) 2010, Jonathan Baldwin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Based on the Libavformat API example by Fabrice Bellard

* Copyright (c) 2003 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>

//#undef exit

using namespace std;

#include "AVEncoder.h"

AVEncoder::AVEncoder()
{
    m_enable_video        = true;
    m_enable_audio        = false;
    m_width               = 480;
    m_height              = 272;
    m_video_codecid       = CODEC_ID_NONE;
    m_framerate           = 30;
    m_in_pixfmt           = PIX_FMT_RGBA;
    m_out_pixfmt          = PIX_FMT_YUV420P;
    m_sws_flags           = SWS_POINT;
    m_audio_samplerate    = 48000;
    m_audio_channels      = 2;
    m_audio_sampleformat  = SAMPLE_FMT_S16;
    m_samples_setbyuser      = false;
    m_in_picture_setbyuser   = false;
    m_audio_codecid       = CODEC_ID_FLAC;
}

/*
* add an audio output stream
*/
AVStream *AVEncoder::add_audio_stream(enum CodecID codec_id)
{
    AVCodecContext *c;
    AVStream *st;

    st = av_new_stream(m_oc, 1);
    if (!st) {
	rFatal("Could not alloc stream");
    }

    c = st->codec;
    c->codec_id = codec_id;
    c->codec_type = AVMEDIA_TYPE_AUDIO;

    /* put sample parameters */
    c->sample_fmt = m_audio_sampleformat;
    c->bit_rate = 64000;
    c->sample_rate = m_audio_samplerate;
    c->channels = m_audio_channels;

    // some formats want stream headers to be separate
    if (m_oc->oformat->flags & AVFMT_GLOBALHEADER)
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;

    return st;
}

void AVEncoder::open_audio(AVStream *st)
{
    AVCodecContext *c;
    AVCodec *codec;

    c = st->codec;

    /* find the audio encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
	rFatal("codec not found");
    }

    /* open it */
    if (avcodec_open(c, codec) < 0) {
	rFatal("could not open codec");
    }

    /* init signal generator */
    //m_t = 0;
    //m_tincr = 2 * M_PI * 110.0 / c->sample_rate;
    /* increment frequency by 110 Hz per second */
    //m_tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;

    m_audio_outbuf_size = 0x100000;
    m_audio_outbuf = (uint8_t*) av_malloc(m_audio_outbuf_size);

    /* ugly hack for PCM codecs (will be removed ASAP with new PCM
      support to compute the input frame size in samples */
    if (c->frame_size <= 1) {
        m_audio_input_frame_size = m_audio_outbuf_size / c->channels;
        switch (st->codec->codec_id) {
        case CODEC_ID_PCM_S16LE:
        case CODEC_ID_PCM_S16BE:
        case CODEC_ID_PCM_U16LE:
        case CODEC_ID_PCM_U16BE:
            m_audio_input_frame_size >>= 1;
            break;
        default:
            break;
        }
    } else {
        m_audio_input_frame_size = c->frame_size;
    }
    m_audio_frame_bytes = m_audio_input_frame_size * 2 * c->channels;
    if(!m_samples_setbyuser)
      m_samples = (int16_t*) av_malloc(m_audio_frame_bytes);
}

void AVEncoder::writeAudioFrame()
{
    AVStream *st = m_audio_st;
    AVCodecContext *c;
    AVPacket pkt;
    av_init_packet(&pkt);

    c = st->codec;

    pkt.size= avcodec_encode_audio(c, m_audio_outbuf, m_audio_outbuf_size, m_samples);

    if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
        pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
    pkt.flags |= AV_PKT_FLAG_KEY;
    pkt.stream_index= st->index;
    pkt.data= m_audio_outbuf;

    /* write the compressed frame in the media file */
    if (av_interleaved_write_frame(m_oc, &pkt) != 0) {
	rFatal("Error while writing frame");
    }
}

void AVEncoder::close_audio(AVStream *st)
{
    avcodec_close(st->codec);

    if(!m_samples_setbyuser)
      av_free(m_samples);
    av_free(m_audio_outbuf);
}


/* add a video output stream */
AVStream *AVEncoder::add_video_stream(enum CodecID codec_id)
{
    AVCodecContext *c;
    AVStream *st;

    st = av_new_stream(m_oc, 0);
    if (!st) {
	rFatal("Could not alloc stream");
    }

    c = st->codec;
    c->codec_id = codec_id;
    c->codec_type = AVMEDIA_TYPE_VIDEO;

    /* put sample parameters */
    c->bit_rate = 400000;
    /* resolution must be a multiple of two */
    c->width = m_width;
    c->height = m_height;
    /* time base: this is the fundamental unit of time (in seconds) in terms
      of which frame timestamps are represented. for fixed-fps content,
      timebase should be 1/framerate and timestamp increments should be
      identically 1. */
    c->time_base.den = m_framerate;
    c->time_base.num = 1;
    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
    c->pix_fmt = m_out_pixfmt;
    if (c->codec_id == CODEC_ID_MPEG2VIDEO) {
        /* just for testing, we also add B frames */
        c->max_b_frames = 2;
    }
    if (c->codec_id == CODEC_ID_MPEG1VIDEO) {
        /* Needed to avoid using macroblocks in which some coeffs overflow.
          This does not happen with normal video, it just happens here as
          the motion of the chroma plane does not match the luma plane. */
        c->mb_decision=2;
    }
    // some formats want stream headers to be separate
    if (m_oc->oformat->flags & AVFMT_GLOBALHEADER)
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;

    return st;
}

AVFrame *AVEncoder::alloc_picture(enum PixelFormat pix_fmt, int width, int height)
{
    AVFrame *picture;
    uint8_t *picture_buf;
    int size;

    picture = avcodec_alloc_frame();
    if (!picture)
        return NULL;
    size = avpicture_get_size(pix_fmt, width, height);
    picture_buf = (uint8_t*) av_malloc(size);
    if (!picture_buf) {
        av_free(picture);
        return NULL;
    }
    avpicture_fill((AVPicture *)picture, picture_buf,
                   pix_fmt, width, height);
    return picture;
}

void AVEncoder::open_video(AVStream *st)
{
    AVCodec *codec;
    AVCodecContext *c;

    c = st->codec;

    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
	rFatal("codec not found");
    }

    /* open the codec */
    if (avcodec_open(c, codec) < 0) {
	rFatal("could not open codec");
    }

    m_video_outbuf = NULL;
    if (!(m_oc->oformat->flags & AVFMT_RAWPICTURE)) {
        /* allocate output buffer */
        /* XXX: API change will be done */
        /* buffers passed into lav* can be allocated any way you prefer,
          as long as they're aligned enough for the architecture, and
          they're freed appropriately (such as using av_free for buffers
          allocated with av_malloc) */
        m_video_outbuf_size = 200000;
        m_video_outbuf = (uint8_t*) av_malloc(m_video_outbuf_size);
    }

    /* allocate the encoded raw picture */
    m_out_picture = alloc_picture(c->pix_fmt, c->width, c->height);
    if (!m_out_picture) {
	rFatal("Could not allocate output frame");
    }

    if(!m_in_picture_setbyuser)
    {
	m_in_picture = avcodec_alloc_frame();
	if (!m_in_picture)
	{
	  rFatal("Could not allocate input frame");
	}
	/*if (m_in_picture_buffer)
	    avpicture_fill((AVPicture*)m_in_picture, (uint8_t*) m_in_picture_buffer, m_in_pixfmt, c->width, c->height);
	else */
	if (avpicture_alloc((AVPicture*)m_in_picture, m_in_pixfmt, c->width, c->height)<0)
	{
	  rFatal("Could not allocate input frame data");
	}
    }
}

void AVEncoder::writeVideoFrame()
{
    AVStream *st = m_video_st;
    int out_size, ret;
    AVCodecContext *c;
    static struct SwsContext *img_convert_ctx;

    c = st->codec;

    /* as we only generate a YUV420P picture, we must convert it
      to the codec pixel format if needed */
    if (img_convert_ctx == NULL) {
        img_convert_ctx = sws_getContext(c->width, c->height,
                                         m_in_pixfmt,
                                         c->width, c->height,
                                         c->pix_fmt,
                                         m_sws_flags, NULL, NULL, NULL);
        if (img_convert_ctx == NULL) {
	    rFatal("Cannot initialize the conversion context");
        }
    }
    //fill_yuv_image(m_in_picture, m_frame_count, c->width, c->height);
    sws_scale(img_convert_ctx, m_in_picture->data, m_in_picture->linesize,
              0, c->height, m_out_picture->data, m_out_picture->linesize);

    if (m_oc->oformat->flags & AVFMT_RAWPICTURE) {
        /* raw video case. The API will change slightly in the near
          futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

        pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.stream_index= st->index;
        pkt.data= (uint8_t *)m_out_picture;
        pkt.size= sizeof(AVPicture);

        ret = av_interleaved_write_frame(m_oc, &pkt);
    } else {
        /* encode the image */
        out_size = avcodec_encode_video(c, m_video_outbuf, m_video_outbuf_size, m_out_picture);
        /* if zero size, it means the image was buffered */
        if (out_size > 0) {
            AVPacket pkt;
            av_init_packet(&pkt);

            if (c->coded_frame->pts != AV_NOPTS_VALUE)
                pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
            if (c->coded_frame->key_frame)
                pkt.flags |= AV_PKT_FLAG_KEY;
            pkt.stream_index= st->index;
            pkt.data= m_video_outbuf;
            pkt.size= out_size;

            /* write the compressed frame in the media file */
            ret = av_interleaved_write_frame(m_oc, &pkt);
        } else {
            ret = 0;
        }
    }
    if (ret != 0) {
	rFatal("Error while writing video frame");
    }
    m_frame_count++;
}

void AVEncoder::write_delayed_video_frames(AVStream *st)
{
    int out_size, ret;
    AVCodecContext *c;
    static struct SwsContext *img_convert_ctx;

    c = st->codec;

    //If the format wants raw image data, there can be no delayed frames at the codec level
    if (m_oc->oformat->flags & AVFMT_RAWPICTURE)
        return;
    while (true)
    {
        //pass a null frame in to get a delayed frame, if there is one in the buffer
        out_size = avcodec_encode_video(c, m_video_outbuf, m_video_outbuf_size, 0);

        //if there was nothing, we're done here.
        if (out_size <= 0)
            return;

        AVPacket pkt;
        av_init_packet(&pkt);

        if (c->coded_frame->pts != AV_NOPTS_VALUE)
            pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
        if (c->coded_frame->key_frame)
            pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.stream_index= st->index;
        pkt.data= m_video_outbuf;
        pkt.size= out_size;

        /* write the compressed frame in the media file */
        ret = av_interleaved_write_frame(m_oc, &pkt);

        if (ret != 0) {
	    rFatal("Error while writing video frame");
        }

        rDebug("Wrote delayed frame of size %i", out_size);
    }
}

void AVEncoder::close_video(AVStream *st)
{
    avcodec_close(st->codec);
    av_free(m_out_picture->data[0]);
    av_free(m_out_picture);

    if(!m_in_picture_setbyuser)
    {
      av_free(m_in_picture->data[0]);
      av_free(m_in_picture);
    }

    av_free(m_video_outbuf);
}

/**************************************************************/
/* media file output */

void AVEncoder::open(const char *filename)
{
    //      double /*audio_pts,*/ video_pts;

    /* initialize libavcodec, and register all codecs and formats */
    av_register_all();

    /* auto detect the output format from the name. default is
          mkv. */
    m_fmt = av_guess_format(NULL, filename, NULL);
    if (!m_fmt) {
        rDebug("Could not deduce output format from file extension: using Matroska.");
        m_fmt = av_guess_format("mkv", NULL, NULL);
    }
    if (!m_fmt) {
	rFatal("Could not find suitable output format");
    }

    /* allocate the output media context */
    m_oc = avformat_alloc_context();
    if (!m_oc) {
	rFatal("Memory error");
    }
    m_oc->oformat = m_fmt;
    snprintf(m_oc->filename, sizeof(m_oc->filename), "%s", filename);

    if (m_video_codecid != CODEC_ID_NONE)
        m_fmt->video_codec = m_video_codecid;

    if (m_audio_codecid != CODEC_ID_NONE)
        m_fmt->audio_codec = m_audio_codecid;

    /* add the audio and video streams using the default format codecs
      and initialize the codecs */
    m_video_st = NULL;
    m_audio_st = NULL;
    if (m_enable_video && m_fmt->video_codec != CODEC_ID_NONE) {
        m_video_st = add_video_stream(m_fmt->video_codec);
    }
    if (m_enable_audio && m_fmt->audio_codec != CODEC_ID_NONE) {
        m_audio_st = add_audio_stream(m_fmt->audio_codec);
    }

    /* set the output parameters (must be done even if no
      parameters). */
    if (av_set_parameters(m_oc, NULL) < 0) {
	rFatal("Invalid output format parameters");
    }

    dump_format(m_oc, 0, filename, 1);

    /* now that all the parameters are set, we can open the audio and
      video codecs and allocate the necessary encode buffers */
    if (m_video_st)
        open_video(m_video_st);
    if (m_audio_st)
        open_audio(m_audio_st);

    /* open the output file, if needed */
    if (!(m_fmt->flags & AVFMT_NOFILE)) {
        if (url_fopen(&m_oc->pb, filename, URL_WRONLY) < 0) {
            rFatal("Could not open '%s'\n", filename);
        }
    }

    /* write the stream header, if any */
    av_write_header(m_oc);
}

void AVEncoder::close()
{
    write_delayed_video_frames(m_video_st);
    /* write the trailer, if any.  the trailer must be written
    * before you close the CodecContexts open when you wrote the
    * header; otherwise write_trailer may try to use memory that
    * was freed on av_codec_close() */
    av_write_trailer(m_oc);

    /* close each codec */
    if (m_video_st)
        close_video(m_video_st);
    if (m_audio_st)
        close_audio(m_audio_st);

    /* free the streams */
    for (int i = 0; i < m_oc->nb_streams; i++) {
        av_freep(&m_oc->streams[i]->codec);
        av_freep(&m_oc->streams[i]);
    }

    if (!(m_fmt->flags & AVFMT_NOFILE)) {
        /* close the output file */
        url_fclose(m_oc->pb);
    }

    /* free the stream */
    av_free(m_oc);

    return;
}
